import React, { useMemo, useState } from "react";
import EditPage, { createFields } from "../../Component/ResourceList/Edit";
import { LibAppView, utils } from '@/lib';
import { FormattedMessage } from "react-intl";
import { ActivityMode, ActivityStatus } from "../Activity/Data";
import dayjs from 'dayjs';
import { SelectArticleFormItem, SelectExpertFormItem } from "../Activity/SourceData";
import { message } from "antd";
import { isArray } from "lodash";


const ActivityEdit = LibAppView.withService({
})((props) => {
    const requireRules = useMemo(() => ([{ required: true, message: <FormattedMessage id="admin.pages.article.formItem.required"/>}]), []);

    const fields = useMemo(() =>createFields([{
        label: "活动标题",
        name: "title",
        type: "Input",
        required: true,
        rules: requireRules
    },{
        label: "开始时间",
        name: "startTime",
        type: "Date",
        required: true,
        rules: requireRules
    }, {
        label: "结束时间",
        name: "endTime",
        type: "Date",
        required: true,
        rules: requireRules
    },{
        label: "主办单位",
        name: "hostOrganization",
        type: "Input",
        required: true,
        rules: requireRules
    },{
        label: "活动方式",
        name: "mode",
        type: "Select",
        required: true,
        rules: requireRules,
        props: {
            options: ActivityMode
        }
    }, {
        label: "活动地区",
        name: "region",
        type: "Region",
        required: true,
        rules: requireRules
    },{
        label: "详细地址",
        name: "address",
        type: "Input"
    }, {
        label: "封面",
        name: "cover",
        type: "Cover",
        props: {
            filterType: "image"
        }
    }, {
        label: "内容",
        name: "content",
        type: "RichText"
    }, {
        label: "是否外链",
        name: "isRef",
        type: "Switch",
        props: {
            checkedChildren: "是",
            unCheckedChildren: "否"
        }
    }, {
        label: "外链地址",
        name: "refUrl",
        type: "Input"
    },
    {
        label: "关联资源",
        name: "articles",
        type: "Custom",
        fullColumn: true,
        Component: SelectArticleFormItem
    }, {
        label: "关联专家",
        name: "resources",
        type: "Custom",
        fullColumn: true,
        Component: SelectExpertFormItem
    }]),[]);
    const journeyData = LibAppView.useJourneyData();
    const editData = journeyData.currentStepState || {};
     const [ currentUserId ]= useState(() => {
            const userData = JSON.parse(sessionStorage.getItem("AdminData") || "{}");
            return userData.userId;
        });
    const isCreator = useMemo(() => {
        return editData?.createUser === currentUserId && editData?.taskUser !== currentUserId;
    },[editData, currentUserId]);

    return (
        <EditPage
            submitEndPoint="activity.submit"
            fields={fields}
            initValues={{
                dataType: "specialType",
                isRef: 0,
                status: 0
            }}
            submitText="申报入库"
            hideSubmit={isCreator}
            buildRequest={(formData: any) => {
                const submitData = {
                    ...formData,
                    isRef: formData.isRef ? 1 : 0,
                    region: utils.jsonToStr(formData.region),
                    status: /^[\d]+$/.test(formData.status) ? formData.status : 0,
                    applyUser: formData.createUser
                };
                delete submitData.id;
                return submitData;
            }}
            buildResponse={(response: any) => {
                return {
                    ...response,
                    isRef: response.isRef === 1,
                    startTime: response.startTime && dayjs(response.startTime),
                    endTime: response.endTime && dayjs(response.endTime)
                }
            }}
            afterSubmit={(response: any) => {
                return new Promise((resolve,reject) => {
                    props.withServiceApi.send({
                        endPoint: "activity.applyUpdate",
                        data: {
                            ...response,
                            status: 3
                        }
                    }).then(resolve).catch(reject);
                });
            }}
            actionButtons={[{
                label: "完善信息",
                props: {type: "primary"},
                type: isCreator ? "primary" : "default",
                onClick: (formData: any, defaultData) => {
                    return new Promise((resolve,reject) => {
                        const expertList = isArray(formData.resources) ? formData.resources?.map((v: any) => v.id) : [];
                        const articleList = isArray(formData.articles) ? formData.articles?.map((v: any) => v.id) : [];
                        props.withServiceApi.send({
                            endPoint: "activity.applyUpdate",
                            data: {
                                ...formData,
                                id: defaultData.id,
                                expert: JSON.stringify(expertList),
                                articleList: JSON.stringify(articleList)
                            }
                        }).then(() => {
                            message.success("信息更新成功");
                            resolve({});
                        }).catch((err) => {
                            message.success(err.message || "信息更新失败");
                            reject({});
                        });
                    });
                }
            }]}
        />
    )
});

export default ActivityEdit;

